package com.soulless.array;

/**
 * @author zenglei
 * @Description 功能描述    选择排序
 * 1. 在未排序序列中找到最小（大）元素，存放到排序序列的起始位置。
 * 2. 再从剩余未排序元素中继续寻找最小（大）元素，存放到已排序序列的末尾。
 * 3. 重复1，2
 * @date 2020/11/25 19:55
 */
public class SelectionSort {

    private long[] arr;
    private int length;

    public SelectionSort(int length) {
        this.arr = new long[length];
    }

    public void insert(long value) {
        this.arr[length] = value;
        this.length++;
    }

    public void display() {
        for (int i = 0; i < this.arr.length; i++) {
            System.out.print(this.arr[i] + " ");
        }
        System.out.print("\n");
    }

    public void selectionSort() {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[minIndex] > arr[j]) {
                    minIndex = j;
                }
            }
            swap(i, minIndex);
        }
    }

    private void swap(int one, int two) {
        long temp = arr[one];
        arr[one] = arr[two];
        arr[two] = temp;
    }

}

class TestSelectionSort {
    public static void main(String[] args) {
        SelectionSort bs = new SelectionSort(5);
        for (int i = 0; i < 5; i++) {
            long r = (long) (Math.random()*100);
            bs.insert(r);
        }
        bs.display();
        bs.selectionSort();
        bs.display();
    }
}
